<template>
    <div class="have-footer loan-in-apply">
        <!-- money-amount -->
        
        
        <div class="loan-index-main" v-if='hasMain'>
            <!-- 我的求借款 -->
            
            <h1 class="big-title" v-if='main.myPublish.records.length || main.myPublish.records.length'>我发布的求借款</h1>
            <template v-if='main.myPublish.records && main.myPublish.records.length'>
                <div class="card fundraising-card nail2" 
                    v-for='item in main.myPublish.records' 
                    @click='goLoanInDetailMe(item.borrowNo)'>
                    <div class="card__header">
                        <div class="loan-money">
                            <p class="loan-money__amount orange">{{ item.borrowAmount | toYuan }}元</p>
                            <p class="loan-money__info"><i>{{ item.borrowDays }}{{item.daysTypeStr}}</i><i>{{ item.yearRate / 100 }}%年化</i></p>
                        </div>
                        <div class="fundraising-info">
                            <p class='font-body1'>{{ item.borrowStateStr }}</p>
                            <div class='font-caption'>
                                <p>有效期: </p><count-down :date='item.borrowEffectiveTime'></count-down>
                            </div>
                        </div>
                    </div>
                    <ul class="card__info">
                        <li class="card__info-item">发布日期：{{ item.createdAt | dateFormat }}</li>
                        <li class="card__info-item">借款用途：{{ item.borrowUsage }}</li>
                        <li class="card__info-item">服务费：{{ item.serviceFee | toYuan }}元</li>
                        <li class="card__info-item">还款方式：{{ item.repayWayStr }}</li>
                        <li class="card__info-item">所有人可见：{{ item.public | booleanToStr }}</li>
                    </ul>
                    <div class="card__share"><span @click.stop='share(item)' class="button short">分享借款</span></div>
                </div>
            </template>
            <h1 class="big-title" v-if='main.myApply.records.length || main.myApply.records.length'>我正在申请的借款</h1>
            <template v-if='main.myApply.records && main.myApply.records.length'>
                <div class="card fundraising-card nail2" 
                    v-for='item in main.myApply.records' 
                    @click='goLoanInDetailMe(item.borrowNo,item.lendNo)'>
                    <div class="card__header">
                        <div class="loan-money">
                            <p class="loan-money__amount orange">{{ item.borrowAmount | toYuan }}元</p>
                            <p class="loan-money__info"><i>{{ daysTransform(item.borrowDays) }}</i><i>{{ item.yearRate / 100 }}%年化</i></p>
                        </div>
                        <div class="fundraising-info">
                            <p class='font-body1'>{{ item.borrowStateStr }}</p>
                            <div class='font-caption'>
                                <p>有效期: </p><count-down :date='item.borrowEffectiveTime'></count-down>
                            </div>
                        </div>
                    </div>
                    <ul class="card__info">
                        <li class="card__info-item">发布日期：{{ item.createdAt | dateFormat }}</li>
                        <li class="card__info-item">借款用途：{{ item.borrowUsage }}</li>
                        <li class="card__info-item">服务费：{{ item.serviceFee | toYuan }}元</li>
                        <li class="card__info-item">还款方式：{{ item.repayWayStr }}</li>
                        <li class="card__info-item">所有人可见：{{ item.public | booleanToStr }}</li>
                    </ul>
                </div>
            </template>
            <h1 class="big-title" v-if='main.rejected.records.length || main.rejected.records.length'>已被拒绝的借款</h1>
            <template v-if='main.rejected.records && main.rejected.records.length'>
                <div class="card fundraising-card nail2" 
                    v-for='item in main.rejected.records' 
                    @click='goLoanInDetailMe(item.borrowNo,item.lendNo)'>
                    <div class="card__header">
                        <div class="loan-money">
                            <p class="loan-money__amount orange">{{ item.borrowAmount | toYuan }}元</p>
                            <p class="loan-money__info"><i>{{ daysTransform(item.borrowDays) }}</i><i>{{ item.yearRate / 100 }}%年化</i></p>
                        </div>
                        <div class="fundraising-info">
                            <p class='font-body1'>{{ item.borrowStateStr }}</p>
                            <div class='font-caption'>
                                <p>有效期: </p><count-down :date='item.borrowEffectiveTime'></count-down>
                            </div>
                        </div>
                    </div>
                    <ul class="card__info">
                        <li class="card__info-item">发布日期：{{ item.createdAt | dateFormat }}</li>
                        <li class="card__info-item">借款用途：{{ item.borrowUsage }}</li>
                        <li class="card__info-item">服务费：{{ item.serviceFee | toYuan }}元</li>
                        <li class="card__info-item">还款方式：{{ item.repayWayStr }}</li>
                        <li class="card__info-item">所有人可见：{{ item.public | booleanToStr }}</li>
                    </ul>
                </div>
            </template>
        </div>
            
        <!-- <template v-if='recommend.length'>
            <h1 class="big-title">
                <p>为你推荐<i class='title-number'>{{totalCount}}个</i>优质出借方</p>
                <div class='switch-loading' v-if='loading_switch'><loading :size='12'></loading></div>
                <i class='title-switch' v-else @click='switchRecommend'>换一批</i>
            </h1>
            <div class="recommend-box">
                <div class='recommend'>
                    <div class="recommend__item" v-for='item in recommend' @click='goRecommend(item)'>
                        <img :src="item.user.avatar || placeholderImg">
                        <p>{{item.user.realName || placeholder}}</p>
                        <span v-if='item.lend'>{{item.lend.lendAmountFrom | toYuanInt}} - {{item.lend.lendAmountTo | toYuanInt}}元</span>
                        <span v-else></span>
                        <i>找TA借</i>
                    </div>
                </div>
            </div>
        </template> -->

        <p class="page-placeholder" v-if='allEmpty && pageLoaded'>
            <span>暂无借款记录</span>
        </p>
    </div>
</template>

<script>
    import { Promise } from 'es6-promise'
    import footerBar from '../components/FooterBar.vue'
    import selectGroup from '../components/SelectGroup.vue'
    import selectOption from '../components/SelectOption.vue'
    import radioGroup from '../components/RadioGroup.vue'
    import areaSelect from '../components/AreaSelect.vue'
    import radio from '../components/Radio.vue'
    import loading from '../components/Loading.vue'
    import checkBox from '../components/CheckBox.vue'
    import toolTip from '../components/ToolTip.vue'
    import modal from '../components/Modal.vue'
    import confirm from '../components/Confirm.vue'
    import buttonLoading from '../components/ButtonLoading.vue'
    import pagination from '../components/Pagination.vue'
    import payPassword from '../components/PayPassword.vue'
    import countDown from '../components/CountDown.vue'
    import slide from '../components/Slide.vue'
    import toYuan from '../filters/filter-toYuan'
    import booleanToStr from '../filters/filter-booleanToStr'
    import dateFormat from '../filters/filter-dateFormat'
    import  { mapGetters, mapActions }  from 'vuex'
    import { addLenderValidation, resetAccountPasswordValidation, operatorEditValidation } from '../validation/validation'
    import { loanOutApi, messageApi } from '../api/api'
    import moment from 'moment'

    export default {
        components:{
            footerBar,
            selectGroup,
            selectOption,
            radioGroup,
            radio,
            checkBox,
            areaSelect,
            loading,
            toolTip,
            modal,
            confirm,
            slide,
            buttonLoading,
            pagination,
            payPassword,
            countDown,
        },
        filters:{
            toYuan,
            booleanToStr,
            dateFormat,
            diffDay(time){
                let now = moment()
                let day = moment(time)
                let diff = day - now
            },
            toYuanInt(money){
                if(money === 0) return '0'
                else if(!money) return '0'
                else if(money >= 1000000){
                    return Number((money/1000000).toFixed(2)) + '万'
                }
                else return Number((money/100).toFixed(2))
            }

        },
        data() {
            return {
                main:{},
                currentPage:'',
                totalPage:'',
                totalCount:'',
                placeholderImg:require('../images/loading_1.png'),
                currentImg:'',
                pageLoaded:false,
                currentText:'',
                payPasswordShow:false,
                messageShow:true,
                loading_switch:false,
                messageList:[],
                messageIndex:0,
                payStatus:'',
                recommend:[],
                password:'',
                placeholder:'--',
                userCount:'',
                listInfo:{},
                records:[],
                loading:true,
                loading_count:true,
            }
        },
        computed:{
            ...mapGetters([
                'msgTip',
                'localInfo',
            ]),
            currentPage(){
                if(_.isEmpty(this.listInfo)) return 1
                return this.listInfo.pageNum
            },
            channel(){
                return this.localInfo.channel
            },
            userInfo(){
                return this.localInfo.userInfo
            },
            hasMain(){
                return !_.isEmpty(this.main)
            },
            allEmpty(){
                if(_.isEmpty(this.main)){
                    return true
                }
                else{
                    let len1 = this.main.myApply.records.length
                    let len2 = this.main.myPublish.records.length
                    let len3 = this.main.rejected.records.length

                    if(!len1 && !len2 && !len3 ){
                        return true
                    }
                }
                return false
            },
            needLogin(){
                return this.localInfo.needLogin
            },
        },
        methods:{
            // actions
            ...mapActions([
                'showLoading',
                'hideLoading',
                'setMsgTip',
                'setShare',
                'showShare',
            ]),

            // function
            daysTransform(days){

                let str
                if(days >= 30){
                    str = days / 30 + '个月'

                }
                else{
                    str = days + '天'
                }
                return str
                
            },

            withinOneDay(time){
                let now = moment()
                let diff = moment(time)
                let diffDays = diff.diff(now,'days')
                let diffTime = diff.diff(now)
                if(diffDays <= 0) return true
                return diffDays
                return true
            },
            goLoanInDetailMe(number,lendNo){
                this.$router.push({
                    name:'loan-in-detail-me',
                    params:{
                        number:number
                    },
                    query:{
                        lendNo:lendNo
                    }
                })
            },
            goLoanInDetailOther(number){
                this.$router.push({
                    name:'loan-in-detail-other',
                    params:{
                        number:number
                    }
                })
            },
            goRecommend(item){
                if(!this.checkLogin()) return
                    
                this.$ga.event({
                  eventCategory: 'link',
                  eventAction: 'click',
                  eventLabel: 'borrowRecommend - ' + this.channel + '-' + item.user.realName + '-' + item.user.userId
                })

                let user = item.user
                let lend = item.lend
                if(!lend){
                    this.$router.push({
                        name:'contact-detail',
                        params:{
                            id:user.uuid,
                        },
                        query:{
                            type:'add'
                        }
                    })
                }
                else{
                    this.$router.push({
                        name:'loan-out-detail-other',
                        params:{
                            number:lend.lendNo
                        },
                        query:{
                            type:'add'
                        }
                    })
                }
            },
            share(item){
                let protocol = location.protocol
                let host = location.host
                let pathname = location.pathname
                let search = location.search

                let realUrl = `${protocol}//${host}${pathname}${search}#share-loan-in/${item.borrowNo}`
                this.setShare({
                    message:{
                        title: '求借款啊！我正在有借求借款，赶紧来借给我吧！', // 分享标题
                        desc: `金额: ${toYuan(item.borrowAmount)},时长: ${dateFormat(item.createdAt)}- ${dateFormat(item.borrowEffectiveTime)}, 利率: ${(item.yearRate / 100).toFixed(2)}%, 用途: ${item.borrowUsage}`, // 分享描述
                        link: realUrl, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                        imgUrl: 'https://youjie.kongapi.com/pic/loading_1.png', // 分享图标
                        type: '', // 分享类型,music、video或link，不填默认为link
                        dataUrl: '', // 如果type是music或video，则要提供数据链接，默认为空
                        success: function () { 

                        },
                        cancel: function () { 

                        }
                    },
                    timeline:{
                        title: '求借款啊！我正在有借求借款，赶紧来借给我吧！', // 分享标题
                        link: realUrl, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                        imgUrl: 'https://youjie.kongapi.com/pic/loading_1.png', // 分享图标
                        success: function () { 
                            
                        },
                        cancel: function () { 

                        }
                    },
                    qq:{
                        title: '求借款啊！我正在有借求借款，赶紧来借给我吧！', // 分享标题
                        desc: `金额: ${toYuan(item.borrowAmount)},时长: ${dateFormat(item.createdAt)}- ${dateFormat(item.borrowEffectiveTime)}, 利率: ${(item.yearRate / 100).toFixed(2)}%, 用途: ${item.borrowUsage}`, // 分享描述
                        link: realUrl, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                        imgUrl: 'https://youjie.kongapi.com/pic/loading_1.png', // 分享图标
                        success: function () { 
                            
                        },
                        cancel: function () { 

                        }
                    },
                })
                this.showShare()
            },
            goRouter(name){
                if(!this.checkLogin()) return

                this.$router.push({
                    name:name
                })
            },
            goLoanInWant(){
                if(!this.check()) return
                
                this.$router.push({
                    name:'loan-in-want-index',
                    params:{
                        number:'default'
                    }
                })
            },
            goMessageDetail(event){
                let el = $(event.target).closest('.swiper-slide')
                if(!el.length) return

                let id = el.data('id')

                this.$router.push({
                    name:'message-box-detail',
                    params:{
                        id:id
                    }
                })
            },
            checkLogin(){
                if(this.needLogin){
                    this.$router.push({
                        name:'bind-phone'
                    })
                    return false
                }
                return true
            },
            check(){
                if(this.needLogin){
                    this.$router.push({
                        name:'bind-phone'
                    })
                    return false
                }
                if(this.hasMain){
                    if(this.main.myPublish.records.length){
                        this.setMsgTip({
                            text:'有正在发布的借款，请勿重复发布',
                            type:'warn'
                        })
                        return false
                    }
                }
                return true
            },
            goDetailMe(){
            },
            goPay(){
                this.payStatus = true
                console.log(1)
            },
            goLoanOutDetailOther(user){
                this.$router.push({
                    name:'loan-out-detail-other',
                    params:{
                        id:user.uuid,
                    },
                    query:{
                        type:'add'
                    }
                })
            },
            goDetail(item){
                this.$router.push({
                    name:'user-detail',
                    params:{
                        id:item.userId,
                    }
                })
            },
            getMain(){
                this.showLoading()
                loanInApi.myBorrowApplying()
                .then(result=>{
                    this.main = result
                    this.pageLoaded=true
                    this.hideLoading()
                })
                .catch(error => {
                    console.error(error)
                    this.pageLoaded=true
                    this.hideLoading()
                })
            },
            getMessage(){
                messageApi.unReadList()
                .then(result=>{

                    this.messageList = result
                })
                .catch(error => {
                    console.error(error)
                })
            },
            getRecommend(num){
                this.loading_switch = true
                loanOutApi.lendRecommend({
                    pageNo:num
                })
                .then(result=>{
                    this.recommend = result.records
                    this.currentPage = result.pageNum
                    this.totalPage = result.totalPage
                    this.totalCount = result.totalCount
                    this.loading_switch = false

                })
                .catch(error => {
                    console.error(error)
                    this.loading_switch = false
                })
            },
            switchRecommend(){
                if(this.currentPage == this.totalPage){
                    this.currentPage = 1
                    this.getRecommend(this.currentPage)
                    return
                }
                this.currentPage = this.currentPage + 1
                this.getRecommend(this.currentPage)
            }
        },
        created(){
            this.getMain()
        }
    }
</script>

<style lang="scss">
    @import "../sass/variables";
    @import "../sass/extends";
    @import "../sass/mixins";
    .loan-in-apply{
        .card-want-loan{
            margin-top: 16px;
        }
        .fundraising-info{
            color:rgba(#000,.54);
            .font-body1{
                color:$orange;
            }
            .font-caption{
                display: flex;
            }
        }
        .want-loan{
            padding-top: 6px;
        }
        .want-loan__button{
            @extend %font-button;
            transition:background ease .3s;
            display: block;
            margin:0 auto;
            color: #fff;
            text-align: center;
            background:$orange;
            box-shadow:0 0 2px 0 rgba(0,0,0,0.12), 0 2px 2px 0 rgba(0,0,0,0.12);
            border-radius:2px;
            width:159px;
            line-height:35px;
            &:active{
                background-color: darken($orange,5%);
            }
        }
        .want-loan__text{
            @extend %font-caption;
            padding-top: 6px;
            text-align: center;
        }
        .placeholder{
            padding-top: 48px;
            text-align: center;
            p{
                @extend %font-caption;
                padding-top: 6px;
            }
        }
    }

</style>
